package com.liveneo.adapter.mobile.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.liveneo.adapter.base.entity.PrpmVersion;
import com.liveneo.adapter.base.mapper.PrpmVersionMapper;
import com.liveneo.adapter.base.support.LogUtils;
import com.liveneo.adapter.mobile.service.VersionService;
import com.liveneo.adapter.mobile.util.Constant;
import com.liveneo.system.base.utils.OssManage;

@Service
public class VersionServiceImpl implements VersionService {
    @Autowired
    private PrpmVersionMapper prpmVersionMapper;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public List<PrpmVersion> getValidVersions(PrpmVersion record) {
        Map paramMap = new HashMap();
        paramMap.put("effectDate", record.getEffectDate());
        paramMap.put("nowTime", new Date());
        paramMap.put("appType", record.getAppType());
        paramMap.put("systemCode", record.getSystemCode());
        paramMap.put("validStatus", record.getValidStatus());
        paramMap.put("flag", record.getFlag());
        return prpmVersionMapper.selectByVersion(paramMap);
    }

    @Override
    public PrpmVersion getVersion(String versionId, String appType, String systemCode) {
        PrpmVersion prpmVersion = new PrpmVersion();
        prpmVersion.setVersionId(versionId);
        prpmVersion.setSystemCode(systemCode);
        prpmVersion.setAppType(appType);
        return prpmVersionMapper.selectByVersionBean(prpmVersion);
    }

    @Override
    public List<PrpmVersion> getAllVersions(int pageNum, int pageSize, PrpmVersion prpmVersion) {
        PageHelper.startPage(pageNum, pageSize);
        return prpmVersionMapper.selectAllByBean(prpmVersion);
    }

    @Override
    public void addVersion(PrpmVersion version) {
        prpmVersionMapper.insert(version);
    }

    @Override
    public List<PrpmVersion> getAllVersions() {
        return prpmVersionMapper.selectAll();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public List<PrpmVersion> selectlatestVersion(String appType, String systemCode) {
        Map paramMap = new HashMap();
        paramMap.put("nowTime", new Date());
        paramMap.put("appType", appType);
        paramMap.put("systemCode", systemCode);
        return prpmVersionMapper.selectlatestVersion(paramMap);
    }

    @Override
    public void addIpaAndPlistVersionRec(File updateFile, String tmpIpaUrl, String mimeType, String version_Id, String versionConten, Date effectDate,
            String packageName, String appType, String systemCode, String downloadUrl, String mandatoryUpgrade) {
        OssManage ossManage = new OssManage();
        String realIpaURL = "";
        String message = "";
        String loguuid = UUID.randomUUID().toString();
        InputStream in = null;
        InputStream plistin = null;
        try {
            LogUtils.info("上传ipa文件>addIpaAndPlistVersionRec>loguuid=" + loguuid);
            /** 上传ipa文件 */
            in = new FileInputStream(updateFile);
            ossManage.uploadFile(in, tmpIpaUrl, mimeType, loguuid);
            PrpmVersion version = new PrpmVersion();
            version.setVersionId(version_Id);
            version.setVersionConten(versionConten);
            version.setEffectDate(effectDate);
            version.setCreateDate(new Date());
            version.setUptPkgFile(packageName);
            version.setDownloadUrl(tmpIpaUrl);// 更新包下载URL
            version.setAppType(appType);
            version.setSystemCode(systemCode);
            version.setValidStatus("1");
            version.setMandatoryUpgrade(mandatoryUpgrade);// 是否强制更新
            prpmVersionMapper.insert(version);
            message = "IPAUPLOADSUCCESS";
            realIpaURL = ossManage.getIpaURl(tmpIpaUrl);
            realIpaURL = realIpaURL.substring(0, realIpaURL.indexOf(".ipa") + 4);
            if (message.indexOf("IPAUPLOADSUCCESS") > -1) {
                /** 上传对应的plist文件 */
                // 上传的plist文件内容
                String plistStr = Constant.PLISTCONTENTONE + realIpaURL + Constant.PLISTCONTENTTWO + version_Id + Constant.PLISTCONTENTTHREE;
                Document doc = DocumentHelper.parseText(plistStr);
                plistin = new ByteArrayInputStream(doc.asXML().getBytes("utf-8"));
                String tmpPlistUrl = downloadUrl + "/" + Constant.PLISTPACKAGENAME;
                mimeType = "plist";
                try {
                    ossManage.uploadFile(plistin, tmpPlistUrl, mimeType, loguuid);
                    version.setDownloadUrl(tmpPlistUrl);
                    prpmVersionMapper.insert(version);
                    message = "SUCCESS";
                } catch (Exception e) {
                    message = "FAIL";
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            message = "FAIL";
            e.printStackTrace();
            LogUtils.error("上传ipa文件-错误>addIpaAndPlistVersionRec>loguuid=" + loguuid + ">error=" + e);
        } finally {
            try {
                if (in != null) in.close();
                if (plistin != null) plistin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void deleteByPrimaryKey(Integer id) {
        prpmVersionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PrpmVersion selectByID(Integer id) {
        return prpmVersionMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByID(PrpmVersion version) {
        return prpmVersionMapper.updateByPrimaryKey(version);
    }
}
